package communication.server;

import communication.client.Client;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ServerRead implements Runnable {
    Map<String, Client> map = new HashMap<>();
    private Socket socket;
    byte[] bytes = new byte[1024];
    int len = 0;
    private String name;
    BufferedInputStream bis;
    BufferedOutputStream bos;

    public ServerRead(Socket socket, Map<String, Client> map) {
        this.socket = socket;
        this.map = map;
    }


    @Override
    public void run() {
        try {
            bis = new BufferedInputStream(socket.getInputStream());
            while ((len = bis.read(bytes)) != -1) {
                name += new String(bytes, 0, len);
            }
            panduan();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void panduan() {
        try {
            bos = new BufferedOutputStream(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (map.get(name) == null) {
            map.put(name, new Client());
            try {
                bos.write("成功".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                bos.write("失败".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
